from datetime import datetime
from pathlib import Path

from PySide6.QtWidgets import (QMessageBox, QWidget, QPushButton, QTableWidget, QGridLayout, QHBoxLayout,
                               QTableWidgetItem,QLabel,QProgressDialog)
from PySide6.QtCore import Qt

from chuliway import ChuliwayBox
from photochuli import is_image_file_by_pillow, chiliimage, huoquchicun
from wenjian import is_folder_cunzai, open_folder


class MainWindow(QWidget):
    """
    主窗口
    """
    def __init__(self):
        super().__init__()
        self.setWindowTitle('图片批量处理')
        self.imagelinks=[]

        self.imagemessages = ["文件路径", "尺寸", "格式", "大小","最后修改时间"]
        self.chuliway={'kuan': 1920,
                       'gao':1080,
                       'kuangaobi':[16,9],
                       'geshi':'no'}

        #输入、输出文件夹
        self.inputfolderlink='./input'
        self.outputfolderlink='./output'

        #页码
        self.pagenum = 0#当前页码
        self.meiyeshujushu = 10#每页数据数
        self.zonggongyeshu = 0#总共页数

        #主窗口显示方式
        self.mainLayout = QGridLayout()

        #按钮
        self.inputbuttons = QHBoxLayout()
        self.outputbuttons = QHBoxLayout()
        self.biaogexianshi = QGridLayout()
        self.open_input_folder_btn = QPushButton("打开输入文件夹")
        self.shuaxinbtn = QPushButton('刷新')
        self.change = QPushButton("转换")
        self.open_output_folder_btn = QPushButton("打开输出文件夹")
        self.last_page_btn = QPushButton('上一页')
        self.next_page_btn = QPushButton('下一页')

        #图片显示表格
        self.photograth = QTableWidget(0, len(self.imagemessages), self)

        #表格页码显示
        self.pageshow = QLabel()

        self.photograth.setHorizontalHeaderLabels(self.imagemessages)

        for i in range(self.photograth.columnCount()):
            self.photograth.setColumnWidth(i,100)
        self.photograth.setColumnWidth(0,300)
        self.photograth.setColumnWidth(1,100)
        self.photograth.setColumnWidth(2,100)
        self.photograth.setColumnWidth(3,100)
        self.photograth.setColumnWidth(4,140)

        #图片处理方式
        self.chuliwayBox=ChuliwayBox()

        #加入部件
        self.inputbuttons.addWidget(self.open_input_folder_btn)
        self.inputbuttons.addWidget(self.shuaxinbtn)

        self.outputbuttons.addWidget(self.change)
        self.outputbuttons.addWidget(self.open_output_folder_btn)
        self.biaogexianshi.addWidget(self.photograth,0,0,1,3)
        self.biaogexianshi.addWidget(self.last_page_btn,1,0)
        self.biaogexianshi.addWidget(self.pageshow,1,1)
        self.biaogexianshi.addWidget(self.next_page_btn,1,2)

        #主窗口放置部件
        self.mainLayout.addLayout(self.biaogexianshi, 0, 0)
        self.mainLayout.addLayout(self.inputbuttons, 1, 0)
        self.mainLayout.addWidget(self.chuliwayBox,0,1)
        self.mainLayout.addLayout(self.outputbuttons, 1, 1)

        #绑定
        self.bangding()

        self.setLayout(self.mainLayout)

        # 设置窗口大小
        self.resize(1000, 420)
        self.setMinimumSize(400,300)
        self.chuliwayBox.setMaximumWidth(200)

        #初始化
        self.shuaxin()
    def bangding(self):
        """
        绑定函数
        :return:
        """
        self.shuaxinbtn.clicked.connect(self.shuaxin)
        self.open_input_folder_btn.clicked.connect(self.open_input_folder)
        self.open_output_folder_btn.clicked.connect(self.open_output_folder)
        self.change.clicked.connect(self.imagechange)
        self.last_page_btn.clicked.connect(self.shangyiye)
        self.next_page_btn.clicked.connect(self.xiayiye)
    def shangyiye(self):
        if self.pagenum>1:
            self.pagenum=self.pagenum-1
            self.updateshow()
    def xiayiye(self):
        if self.pagenum<self.zonggongyeshu:
            self.pagenum=self.pagenum+1
            self.updateshow()
    def shuaxin(self):
        """
        刷新
        :return:
        """
        self.photograth.clearContents()
        self.photograth.setRowCount(0)
        self.imagelinks.clear()

        inputpath=Path(self.inputfolderlink)
        row_index=0
        for file_path in inputpath.rglob('*'):
            """
            查询文件
            """
            if file_path.is_file and is_image_file_by_pillow(file_path):
                # 将信息添加到图片链接列表（如果需要）
                self.imagelinks.append(file_path)
                print(file_path)
                print(type(file_path))
                row_index += 1
        self.photograth.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.zonggongyeshu= (len(self.imagelinks)//self.meiyeshujushu+1)
        print(self.zonggongyeshu)
        self.pagenum=1
        self.updateshow()
    def updateshow(self):
        """
        根据当前页数和每页显示的图片数更新表格内容
        """
        start_index = (self.pagenum-1) * self.meiyeshujushu
        end_index = start_index + self.meiyeshujushu

        self.photograth.clearContents()
        self.photograth.setRowCount(0)

        for i in range(start_index, end_index):
            if i < len(self.imagelinks):
                file_path = self.imagelinks[i]
                file_extension = file_path.suffix[1:]
                file_size = file_path.stat().st_size
                file_mtime = datetime.fromtimestamp(file_path.stat().st_mtime).strftime('%Y-%m-%d %H:%M:%S')
                photosize = huoquchicun(file_path)

                self.photograth.insertRow(self.photograth.rowCount())
                self.photograth.setItem(self.photograth.rowCount() - 1, 0, QTableWidgetItem(str(file_path)))
                self.photograth.setItem(self.photograth.rowCount() - 1, 1, QTableWidgetItem(photosize))
                self.photograth.setItem(self.photograth.rowCount() - 1, 2, QTableWidgetItem(file_extension))
                self.photograth.setItem(self.photograth.rowCount() - 1, 3, QTableWidgetItem(f"{file_size} bytes"))
                self.photograth.setItem(self.photograth.rowCount() - 1, 4, QTableWidgetItem(file_mtime))

        self.photograth.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.pageshow.setText(str(self.pagenum)+'/'+str(self.zonggongyeshu))
        if self.pagenum<=1:
            self.last_page_btn.setEnabled(False)
        else:
            self.last_page_btn.setEnabled(True)
        if self.pagenum>=self.zonggongyeshu:
            self.next_page_btn.setEnabled(False)
        else:
            self.next_page_btn.setEnabled(True)

    def imagechange(self):
        """
        图片处理
        :return:
        """
        self.shuaxin()
        self.chuliway = self.chuliwayBox.getchuliway()
        print(self.chuliway)

        # 创建进度对话框
        progress = QProgressDialog("处理图片中...", "取消", 0, len(self.imagelinks), self)
        progress.setWindowTitle("请稍候")
        progress.setWindowModality(Qt.WindowModality.WindowModal)  # 设置为模态对话框
        progress.show()

        for index, imagelink in enumerate(self.imagelinks):
            if progress.wasCanceled():
                break  # 如果用户点击了取消按钮，则停止处理

            inputyuanzu = Path(imagelink).parts
            outputyuanzu = ('./output',) + inputyuanzu[1:]
            outputlink = Path('/'.join(outputyuanzu))

            chiliimage(imagelink, outputlink, self.chuliway)

            # 更新进度条
            print(index+1)
            progress.setValue(index + 1)

        progress.setValue(len(self.imagelinks))  # 确保进度条达到最大值

        QMessageBox.information(self, "完成", "所有图片已处理完成！",
                                QMessageBox.StandardButton.Ok, QMessageBox.StandardButton.NoButton)

    def open_input_folder(self):
        """
        打开输入文件夹
        :return:
        """
        if is_folder_cunzai(self.inputfolderlink,True):
            try:
                open_folder(self.inputfolderlink)
            except Exception as error:
                QMessageBox.warning(self,"出错","打开文件夹失败，原因：\n    "+
                                    str(error),QMessageBox.StandardButton.Ok,QMessageBox.StandardButton.NoButton)

    def open_output_folder(self):
        """
        打开输出文件夹
        :return:
        """
        if is_folder_cunzai(self.outputfolderlink,True):
            try:
                open_folder(self.outputfolderlink)
            except Exception as error:
                QMessageBox.warning(self,"出错","打开文件夹失败，原因：\n    "+
                                    str(error),QMessageBox.StandardButton.Ok,QMessageBox.StandardButton.NoButton)